package com.hanfengyi.page.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hanfengyi.feign.FastDFSFignClient;
import com.hanfengyi.feign.RedisFeignClient;
import com.hanfengyi.hrm.AjaxResult;
import com.hanfengyi.hrm.CreateFileUtils;
import com.hanfengyi.hrm.VelocityUtils;
import com.hanfengyi.hrm.ZipUtils;
import com.hanfengyi.hrm.constants.RabbitMQConstants;
import com.hanfengyi.page.domain.Pager;
import com.hanfengyi.page.domain.Site;
import com.hanfengyi.page.mapper.PagerMapper;
import com.hanfengyi.page.mapper.SiteMapper;
import com.hanfengyi.page.service.IPagerService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hfy
 * @since 2020-02-26
 */
@Service
public class PagerServiceImpl extends ServiceImpl<PagerMapper, Pager> implements IPagerService {
    @Autowired
    private RedisFeignClient redisFeignClient;

    @Autowired
    private FastDFSFignClient fastDFSFignClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SiteMapper siteMapper;
    /**
     * 静态化页面生成
     * @param key redis存储的数据的key
     * @param templateName 模板文件名字
     */
    @Override
    public void pageStaticAction(String key, String templateName) {
        //2. 拿到模板
        Pager pager = baseMapper.getTemplateByName(templateName);
        if(pager==null && pager.getTemplateUrl().isEmpty()){
            throw new RuntimeException("所需模板获取失败！");
        }

        //3. 从fastdfs上下载模板
        byte[] templateFile = fastDFSFignClient.getTemplateFile(pager.getTemplateUrl());
        if(templateFile==null || templateFile.length==0){
            throw new RuntimeException("文件下载失败！");
        }

        //4. 获得windows文件临时存储路径 C:\Users\Han\AppData\Local\Temp\
        String systemTempPath =System.getProperty("java.io.tmpdir");
        //拼接zip文件存储路径：C:\Users\Han\AppData\Local\Temp\home.zip
        String zipPath = systemTempPath+templateName+".zip";
        try {
            FileCopyUtils.copy(templateFile, CreateFileUtils.createFile(zipPath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //5. 将下载的zip文件解压到当前目录 解压路径：C:\Users\Han\AppData\Local\Temp\templateFile\
        String unzipPath = systemTempPath+"templateFile/";
        try {
            ZipUtils.unZip(zipPath, unzipPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //6. 将下载解压后的模板与数据合并生成html文件
        //6.1 拿到数据
        AjaxResult ajaxResult = redisFeignClient.get(key);
        if(ajaxResult==null || !ajaxResult.isSuccess()){
            throw new RuntimeException("所需数据获取失败！");
        }

        String treeData = ajaxResult.getResultObj().toString();
        Map<String,Object> model = JSONObject.parseObject(treeData, Map.class);
        model.put("staticRoot", unzipPath);
        // model:数据对象 templateFilePathAndName 模板文件的物理路径 targetFilePathAndName 目标输出文件的物理路径
        String templateFilePathAndName = unzipPath+templateName+".vm";  //C:\Users\Han\AppData\Local\Temp\template\templateFile\home.vm
        String targetFilePathAndName = unzipPath+templateName+".html";  //C:\Users\Han\AppData\Local\Temp\template\templateFile\home.html
        VelocityUtils.staticByTemplate(model,templateFilePathAndName, targetFilePathAndName);

        //7. 将合并后的文件上传到fastdfs
        String htmlPathInFastdfs = null;
        try {
            byte[] bytes = FileCopyUtils.copyToByteArray(CreateFileUtils.createFile(targetFilePathAndName));
            if(bytes!=null && bytes.length>0){
                AjaxResult uploadResult = fastDFSFignClient.uploadByBytes(bytes,"html");
                if(!ajaxResult.isSuccess() || ajaxResult.getResultObj()==null){
                    throw new RuntimeException("html文件上传失败");
                }
                htmlPathInFastdfs = uploadResult.getResultObj().toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //8. 集成RabbitMQ，发布消息：文件在fastdfs上的路径，以及站点路径
        Site site = siteMapper.selectById(pager.getSiteId());

        Map<String,String> map = new HashMap<>();
        map.put("htmlPath", htmlPathInFastdfs);
        map.put("sitePath", pager.getPhysicalPath());
       rabbitTemplate.convertAndSend(RabbitMQConstants.EXCHANGE_NAME_DIRECT, site.getSn(), JSON.toJSONString(map));
    }

}
